<?php

class MenuModel
{
    private $menuID;
    
    public function __construct( $menuName )
    {
        $this->menuID = $this->GetMenuID( $menuName );
    }
    
    public function GetMenuItems( $parentID = 0 )
	{
        $menuItems = array();
        
		require_once Settings::DBPath();
        $DB = new Database();
		
        if ( $DB->Connect() )
        {
            $stmt = $DB->Prepare( "SELECT PathID, Name, Text, paths.Order, Parent, MenuID, PageID FROM paths WHERE MenuID = ? AND Parent = ? ORDER BY paths.Order ASC" );
            $stmt->bind_param( "ii", $this->menuID, $parentID );
            $stmt->execute();
			$stmt->bind_result( $row_pathID, $row_name, $row_text, $row_order, $row_parent, $row_menuID, $row_pageID );
			
			while ( $stmt->fetch() )
			{
				$menuItems[] = array(   'id' => $row_pathID,
									'name' => $row_name,
                                    'text' => $row_text,
                                    'order' => $row_order,
                                    'parent' => $row_parent,
                                    'menuID' => $row_menuID,
                                    'pageID' => $row_pageID,
                                    'children' => NULL );
			}
			
            $stmt->close();
            
            $DB->Close();
        }

        $menuItemsCount = count( $menuItems );
        for( $i = 0; $i < $menuItemsCount; $i++ )
        {
            $menuItems[$i]['children'] = $this->GetMenuItems( $menuItems[$i]['id'] );
        }
        
        return $menuItems;
	}
    
    private function GetMenuID( $menuName )
    {
        $menuID = NULL;

        require_once Settings::DBPath();
        $DB = new Database();

        if ( $DB->Connect() )
        {
            $stmt = $DB->Prepare( "SELECT MenuID FROM menus WHERE Name = ?" );
            $stmt->bind_param( "s", $menuName );
            $stmt->execute();
            $stmt->bind_result( $row_menuID );
            $stmt->fetch(); 
            $menuID = $row_menuID;
            $stmt->close();

            $DB->Close();
        }

        return $menuID;
    }
    
    public function GetMenuElements()
    {
        $elements = array();
        
        $menuTheme = file('themes/' . Settings::Theme() . '/menu.txt');
        foreach( $menuTheme as $row )
        {
            $row = trim( $row );
            if ( substr( $row, 0, 2 ) != "//" && substr( $row, 0, 1 ) != "#" && strlen( $row ) > 0 )
            {
                $elementData = explode( ':', $row );
                $elements[trim( $elementData[0] )] = trim( $elementData[1] );
            }
        }
        
        return $elements;
    }
}
